import json

from sqlalchemy.exc import SQLAlchemyError
from be.model import error
from be.model import store
from be.model.store import New_Order
from be.model import db_conn
from sqlalchemy import and_

class Seller(db_conn.DBConn):

    def __init__(self):
        db_conn.DBConn.__init__(self)

    def add_book(self, user_id: str, store_id: str, book_id: str, book_json_str: str, stock_level: int):
        try:
            if not self.user_id_exist(user_id):
                return error.error_non_exist_user_id(user_id)
            if not self.store_id_exist(store_id):
                return error.error_non_exist_store_id(store_id)
            if self.book_id_exist(store_id, book_id):
                return error.error_exist_book_id(book_id)
            new_book = store.Store_Book(store_id=store_id,book_id=book_id,book_info=book_json_str,stock_level=stock_level)
            self.session.add(new_book)
            book = json.loads(book_json_str)
            list = []
            for tag in book.get('tags'):
                if tag.strip() != "":
                    list.append(tag)
            for item in list:
                new_invert = store.invert_index(search_key=item,search_id=book_id,book_title=book['title'],book_author=book['author']
                                                ,book_intro=book['book_intro'],store_id=store_id)
                self.session.add(new_invert)
            book['tags'] = str(list)
            print(book['title'])
            print("shit")
            header =['id','title','author','publisher','original_title','translator','pub_year','pages'
                   ,'price','currency_unit','binding','isbn','author_intro','book_intro','content','tags']
            for i in range(len(header)):
                if(book[header[i]])== None:
                    book[header[i]]= "暂无"
            new_Book = store.Book(book_id=book['id'], title=book['title'],store_id=store_id,
                                  author=book['author'], publisher=book['publisher'],
                                  original_title=book['original_title'], translator=book['translator'],
                                  pub_year=book['pub_year'], pages=book['pages'],
                                  original_price=book['price'], currency_unit=book['currency_unit'],
                                  binding=book['binding'], isbn=book['isbn'],
                                  author_intro=book['author_intro'], book_intro=book['book_intro'],
                                  content=book['content'], tags=book['tags'])

            self.session.add(new_Book)
            self.session.query(store.Store).filter_by(store_id=store_id).update({'stock_level':store.Store.stock_level+1})
            self.session.commit()
        except SQLAlchemyError as e:
            return 528, "{}".format(str(e))
        except BaseException as e:
            return 530, "{}".format(str(e))
        return 200, "ok"

    def add_stock_level(self, user_id: str, store_id: str, book_id: str, add_stock_level: int):
        try:
            if not self.user_id_exist(user_id):
                return error.error_non_exist_user_id(user_id)
            if not self.store_id_exist(store_id):
                return error.error_non_exist_store_id(store_id)
            if not self.book_id_exist(store_id, book_id):
                return error.error_non_exist_book_id(book_id)
            self.session.query(store.Store).filter_by(store_id=store_id).update({'stock_level':add_stock_level})
            self.session.query(store.Store_Book).filter_by(store_id=store_id,book_id=book_id).update({'stock_level':add_stock_level})
            
            # self.conn.execute("UPDATE store SET stock_level = stock_level + ? "
            #                   "WHERE store_id = ? AND book_id = ?", (add_stock_level, store_id, book_id))
            # self.conn.commit()
            self.session.commit()
        except SQLAlchemyError as e:
            return 528, "{}".format(str(e))
        except BaseException as e:
            return 530, "{}".format(str(e))
        return 200, "ok"

    def create_store(self, user_id: str, store_id: str) -> (int, str):
        try:
            if not self.user_id_exist(user_id):
                return error.error_non_exist_user_id(user_id)
            if self.store_id_exist(store_id):
                return error.error_exist_store_id(store_id)
            new_store = store.Store(store_id=store_id,stock_level=0)
            new_user_store = store.User_Store(fk_user_id=user_id,fk_store_id=store_id)
            self.session.add(new_store)
            # self.session.commit()
            self.session.add(new_user_store)
            # self.conn.execute("INSERT into user_store(store_id, user_id)"
            #                   "VALUES (?, ?)", (store_id, user_id))
            # self.conn.commit()
            self.session.commit()
        except SQLAlchemyError as e:
            return 528, "{}".format(str(e))
        except BaseException as e:
            return 530, "{}".format(str(e))
        return 200, "ok"

    def send_out(self, order_id:str, user_id:str):
        session = self.session
        try:
            if not self.user_id_exist(user_id):
                return error.error_non_exist_user_id(user_id)
                
            row = session.query(New_Order).filter(New_Order.order_id==order_id).first()
            if row is None:
                return error.error_invalid_order_id(order_id)
            if row.status != 1:
                return error.error_invalid_order_id(order_id)
            
            row = session.query(New_Order).filter(New_Order.order_id==order_id).update({'status':2})

            if row == 0:
                return error.error_invalid_order_id(order_id)

            session.commit()

        except SQLAlchemyError as e:
            return 528, "{}".format(str(e))
        except BaseException as e:
            return 530, "{}".format(str(e))
        return 200, "ok"